import { reactive, watch } from 'vue'

import type {
  IRuleMeta // 验证
} from '../../types/30-form'

import type { IFormChildMetaList } from '../../types/main'

import type { FormRules } from 'element-plus'

/**
 * 创建表单的验证规则，把字段ID转换为字段名称
 * @param itemMeta 表单子控件的meta
 * @param ruleMeta 表单控件的验证规则
 * @returns 
 */
export default function getRules(
    itemMeta: IFormChildMetaList,
    ruleMeta: IRuleMeta
  ) {
    const rules = reactive<FormRules>({})
    /*
    const rules1 = reactive<FormRules>({
      name: [
        { required: true, message: 'Please input Activity name', trigger: 'blur' },
        { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
        { 
          type: 'array',
          min: 2,
          trigger: ''
        }
      ]
    })
    */

    // 表单子控件的属性，key是字段ID
    // const itemMeta = itemMeta

    for (const key in ruleMeta) {
      const rule = ruleMeta[key]
      rules[itemMeta[key].colName] = rule
    }

    // 监听
    watch(ruleMeta, () => {
      // 删除以前的验证
      for (const key in rules) {
        delete rules[key]
      }
      for (const key in ruleMeta) {
        const rule = ruleMeta[key]
        rules[itemMeta[key].colName] = rule
      }
    })

    return rules
  }